package com.bidevalution.controller.task;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.bidevalution.business.service.BeNoticeTemplateService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.business.service.BeSectionParamsService;
import com.bidevalution.business.service.BeSectionSignService;
import com.bidevalution.dao.entity.BeNoticeTemplate;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.support.context.NoticeTemplateCode;
import com.bidevalution.support.factory.NoiceDataFactory;
import com.chatroom.api.dto.ChatGroupInfoDTO;
import com.chatroom.api.dto.ChatNoticeDataDTO;
import com.chatroom.api.service.ChatGroupInfoApiService;
import com.chatroom.api.service.ChatNoticeDataApiService;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.core.model.Response;
import com.qtp.core.redis.RedisUtil;
import com.qtp.core.util.DateUtil;

//@Component
public class NoticeDataTask {
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Value("${SystemIdentify}")
	private String appKey;
	@Autowired
	private ChatGroupInfoApiService chatGroupInfoApiService;
	@Autowired
	private ChatNoticeDataApiService chatNoticeDataApiService;
	@Autowired
	private BeNoticeTemplateService beNoticeTemplateService;
	@Autowired
	private EnterPriseInfoDubboService enterPriseInfoDubboService;
	@Autowired
	private BeSectionSignService beSectionSignService;
	@Autowired
	private BeSectionParamsService beSectionParamsService;
	private Logger logger = Logger.getLogger(getClass());

	public boolean getIsFinish(NoticeTemplateCode noticeTemplateCode, String groupId, Date finishTime) {
		boolean isFinish = true;
		if (!StringUtils.isEmpty(RedisUtil.get(groupId + noticeTemplateCode.name()))) {
			if (Long.compare(finishTime.getTime(), Long.valueOf(RedisUtil.get(groupId + noticeTemplateCode.name()))) != 0) {
				isFinish = false;
			}
		} else {
			isFinish = false;
		}
		return isFinish;
	}

	/**
	 * 1分钟执行一次
	 * 
	 * @throws Exception
	 */
	//@Scheduled(cron = "0 */1 *  * * * ")
	public void initNoticeData() throws Exception {

		for (BeSectionInfo beSectionInfo : beSectionInfoService.getChatSectionList()) {
			ChatGroupInfoDTO chatGroupInfoDTO = chatGroupInfoApiService.getByBusinessGroupId(appKey,
					beSectionInfo.getSeqId());
			if (chatGroupInfoDTO == null) {
				logger.error("该标段没有同步到互动聊天:" + beSectionInfo.getSectionName());
				continue;
			}
			// 添加通知
			addNoticeData(NoticeTemplateCode.C1001, chatGroupInfoDTO.getGroupId(), new NoiceDataFactory() {
				@Override
				public void add(String groupId, String templateContent) {

					if (!getIsFinish(NoticeTemplateCode.C1001, groupId, beSectionInfo.getBidOpenTime())) {
						// 确保定时发送通告之前不会重新添加通知
						chatNoticeDataApiService.add(templateContent,
								DateUtil.getAfterMinute(beSectionInfo.getBidOpenTime(), -10),
								chatGroupInfoDTO.getGroupId(), NoticeTemplateCode.C1001.name(),false);
						RedisUtil.set(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1001.name(),
								String.valueOf(beSectionInfo.getBidOpenTime().getTime()));
						//设置key值24小时过期
						RedisUtil.expire(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1001.name(), 24 * 60 * 60);
					}

				}
			});
			addNoticeData(NoticeTemplateCode.C1002, chatGroupInfoDTO.getGroupId(), new NoiceDataFactory() {
				@Override
				public void add(String groupId, String templateContent) throws Exception {
					if (!getIsFinish(NoticeTemplateCode.C1002, groupId, beSectionInfo.getBidOpenTime())) {

						Map<String, Object> params = new HashMap<>();
						params.put("ep_org_code", beSectionInfo.getAgentOrgCode());
						// 获取请求中的参数
						Response<Map<String, Object>> response = enterPriseInfoDubboService.getEnterInfo(params);
						templateContent = templateContent.replace("{agentOraName}",
								(String) response.getResult().get("ep_name"));
						templateContent = templateContent.replace("{sectionName}", beSectionInfo.getSectionName());
						templateContent = templateContent.replace("{bidTime}",
								DateUtil.dateToString(beSectionInfo.getBidOpenTime(), "yyyy-MM-dd HH:mm:ss"));
						chatNoticeDataApiService.add(templateContent, beSectionInfo.getBidOpenTime(),
								chatGroupInfoDTO.getGroupId(), NoticeTemplateCode.C1002.name(),false);
						RedisUtil.set(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1002.name(),
								String.valueOf(beSectionInfo.getBidOpenTime().getTime()));
						//设置key值24小时过期
						RedisUtil.expire(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1002.name(), 24 * 60 * 60);
					}
				}
			});
			addNoticeData(NoticeTemplateCode.C1003, chatGroupInfoDTO.getGroupId(), new NoiceDataFactory() {
				@Override
				public void add(String groupId, String templateContent) throws Exception {
					// 签到已经完成进入到后面状态
					if (!getIsFinish(NoticeTemplateCode.C1003, groupId, beSectionInfo.getBidOpenTime())) {
						// 开标时间小于等于当前时间
						if (beSectionInfo.getBidOpenTime().getTime() <= DateUtil.getCurrentTime()) {
							addNoticeData(NoticeTemplateCode.C1003, chatGroupInfoDTO.getGroupId(),
									new NoiceDataFactory() {
										@Override
										public void add(String groupId, String templateContent) {
											templateContent = templateContent.replace("{signCount}",
													beSectionSignService.querySignCount(beSectionInfo.getSeqId()) + "");
											chatNoticeDataApiService.add(templateContent,
													beSectionInfo.getBidOpenTime(), chatGroupInfoDTO.getGroupId(),
													NoticeTemplateCode.C1003.name(),false);
										}
									});
							RedisUtil.set(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1003.name(),
									String.valueOf(beSectionInfo.getBidOpenTime().getTime()));
							//设置key值24小时过期
							RedisUtil.expire(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1003.name(), 24 * 60 * 60);
						}
					}
				}
			});

			addNoticeData(NoticeTemplateCode.C1005, chatGroupInfoDTO.getGroupId(), new NoiceDataFactory() {
				Map<String, String> dataMap = new HashMap<String, String>();

				@Override
				public void add(String groupId, String templateContent) throws Exception {
					if (!NoticeTemplateCode.C1005.name().equals(RedisUtil.get(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1005.name()))
							&&!NoticeTemplateCode.C1007.name().equals(RedisUtil.get(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1007.name()))) {
						dataMap.put("decryptEndTime", beSectionParamsService
								.getBeSectionParamsByCode(beSectionInfo.getSeqId(), "decryptEndTime"));
						if(DateUtil.getAfterMinute(DateUtil.stringToDate(dataMap.get("decryptEndTime"),DateUtil.PT2), -10).getTime() <= DateUtil.getCurrentTime()){
							chatNoticeDataApiService.add(templateContent,
									DateUtil.getAfterMinute(DateUtil.stringToDate(dataMap.get("decryptEndTime"),DateUtil.PT2), -10),
									chatGroupInfoDTO.getGroupId(), NoticeTemplateCode.C1005.name(),false);
							RedisUtil.set(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1005.name(), NoticeTemplateCode.C1005.name());
							//设置key值24小时过期
							RedisUtil.expire(chatGroupInfoDTO.getGroupId() + NoticeTemplateCode.C1005.name(), 24 * 60 * 60);
						} else {
							logger.error("be_section_params表缺少配置代码:decryptStartTime或者decryptTime");
						}

					}

				}
			});

		}

	}

	public void addNoticeData(NoticeTemplateCode noticeTemplateCode, String groupId,
			NoiceDataFactory noiceDataFactory) {
		List<ChatNoticeDataDTO> chatNoticeDataDTOs = chatNoticeDataApiService
				.selectListByCode(noticeTemplateCode.name(), groupId);

		BeNoticeTemplate beNoticeTemplate = beNoticeTemplateService.selectByPrimaryKey(noticeTemplateCode.name());
		if (beNoticeTemplate != null && chatNoticeDataDTOs.size() == 0) {
			try {
				noiceDataFactory.add(groupId, beNoticeTemplate.getContent());
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
	}
}
